/********************************************************************
 * Copyright(c) 2023-2023 Grayson Zheng.
 * File: bit.h
 * Description: PWM output program based on 89C52 timer 2.
 * Version: 1.0
 * Date: 2023-07-25
 * Author: zhengxinyu13@qq.com
 * ---------- Revision History ----------
 * <version>
 * <date>
 * <author>
 * <desc>
 * Modified to be suitable to the new coding rules in all functions.
 ********************************************************************/

#include "PWM_Timer2.h"

uint_16 pwm_cycle = PWM_CYCLE;
uint_16 pwm_duty_ratio = PWM_DUTY_RATIO;
uint_16 pwm_inactive_time = PWM_INACTIVE_TIME;

void time2_init(void)
{
	T2MOD = 0;
	T2CON = 0;
	TL2 = pwm_duty_ratio;
	TH2 = pwm_duty_ratio >> 8;
	RCAP2L = pwm_duty_ratio;
	RCAP2H = pwm_duty_ratio >> 8;
	TR2 = TURN_ON;
	ET2 = TURN_ON;
	EA  = TURN_ON;
}

void set_duty_ratio_xus(uint_16 xus)
{
	uint_16 temp = ((xus / MACHINE_CYCLE) > pwm_cycle ? pwm_cycle : (xus / MACHINE_CYCLE));
	pwm_duty_ratio = temp;
	pwm_inactive_time = pwm_cycle - pwm_duty_ratio;
}

void set_duty_ratio_percentage(fp_32 percentage)
{
	pwm_duty_ratio = percentage * pwm_cycle;
	pwm_inactive_time = pwm_cycle - pwm_duty_ratio;
}

void time2_isr(void) interrupt 5 using 1
{
	PWM_OUTPUT = ~PWM_OUTPUT;
	TF2 = TURN_OFF;

	if (PWM_OUTPUT) {
		RCAP2L = (UINT_16_MAX - pwm_inactive_time);
		RCAP2H = (UINT_16_MAX - pwm_inactive_time) >> 8;
	} else {
		RCAP2L = (UINT_16_MAX - pwm_duty_ratio);
		RCAP2H = (UINT_16_MAX - pwm_duty_ratio) >> 8;
	}
}
